package 题组;

import java.util.Arrays;

/**
 * @author 挚爱之夕
 * @date 2021/9/7 - 09 - 07 - 11:04
 * @Description: 题组
 * @Version: 1.0
 */
public class _001_移动k位旋转数组 {
    public static void main(String[] args) {
        int[] a = new int[]{1,2,3,4,5,6,7};
        int k = 8;
        rotate(a,k);
        int[] a1 = new int[]{1,2,3,4,5,6,7};
        rotate1(a1,k);
        int[] a2 = new int[]{1,2,3,4,5,6,7};
        rotate2(a2,k);
    }
    //自己写的
    private static void rotate(int[] nums, int k) {//慢，内存高
        if(k== nums.length){    //等于没移动
            System.out.println(Arrays.toString(nums));
        }
        if(k> nums.length){
            k%= nums.length;//去除无用移动
        }
        int[] help = new int[k];
        int current = 0;
        //将越过右边界的数字存入辅助数组
        for(int i = nums.length-k;i<nums.length;i++){//i = nums.length-1-k,不对不应该减1
            help[current++] = nums[i];
        }
        //移动未越界数字
        int flag = nums.length-1;
        while(flag-k>=0){
            nums[flag] = nums[flag-k];
            flag--;
        }
        //填入越界数字
        for(int i = 0;i<k;i++){
            nums[i] = help[i];
        }
        System.out.println(Arrays.toString(nums));
    }
    //辅助数组
    private static void rotate1(int[] nums, int k) {
        int n = nums.length;
        int[] newArr = new int[n];
        for (int i = 0; i < n; i++) {
            newArr[(i + k) % n] = nums[i];
        }
//        System.arraycopy(newArr, 0, nums, 0, n);
//        System.out.println(Arrays.toString(nums));
        System.out.println(Arrays.toString(newArr));
    }
    //三次翻转
    private static void rotate2(int[] nums, int k) {
        k %= nums.length;
        reverse(nums, 0, nums.length - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, nums.length - 1);
        System.out.println(Arrays.toString(nums));
    }

    private static void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start += 1;
            end -= 1;
        }
    }
}
